import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:macless_haystack/accessory/accessory_battery.dart';
import 'package:permission_handler/permission_handler.dart';

class AccessoryScan extends StatefulWidget {
  final List<String> macs; // 要跟踪的MAC地址列表

  /// Shows previous locations of a specific [accessory] on a map.
  /// The locations are connected by a chronological line.
  /// The number of days to go back can be adjusted with a slider.
  const AccessoryScan({
    super.key,
    required this.macs,
  });

  @override
  State<StatefulWidget> createState() {
    return _AccessoryScanState();
  }
}

class _AccessoryScanState extends State<AccessoryScan> {
  bool _isScanning = false;
  final Map<String, int> _deviceSignalMap = {}; // 存储设备ID和最新信号强度
  final Map<String, DateTime> _lastUpdateTimes = {};
  final Map<String, AccessoryBatteryStatus?> _deviceBatteryMap = {};
  final _debounceDuration = Duration(milliseconds: 0); // 更短的防抖延迟
  Timer? _debounceTimer; // 防抖定时器
  Timer? _updateTimer; // 时间更新定时器

  @override
  void initState() {
    super.initState();
    _checkBluetoothState();
    // 每秒更新一次时间显示
    _updateTimer = Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {});
    });
  }

  @override
  void dispose() {
    _stopScan();
    _debounceTimer?.cancel();
    _updateTimer?.cancel();
    super.dispose();
  }

  // 格式化时间差为相对时间
  String _formatTimeAgo(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);

    if (difference.inSeconds < 1) {
      return '刚刚';
    } else if (difference.inSeconds < 60) {
      return '${difference.inSeconds}秒前';
    } else if (difference.inMinutes < 60) {
      return '${difference.inMinutes}分${difference.inSeconds % 60}秒前';
    } else {
      return '${difference.inHours}小时前';
    }
  }

  // 蓝牙状态检查
  void _checkBluetoothState() async {
    BluetoothAdapterState state = await FlutterBluePlus.adapterState.first;
    if (state == BluetoothAdapterState.off) {
      _showErrorDialog('蓝牙已关闭，请开启蓝牙');
    }

    FlutterBluePlus.adapterState.listen((state) {
      if (state == BluetoothState.off) {
        _showErrorDialog('蓝牙已关闭，请开启蓝牙');
      }
    });
  }

  // 获取信号强度百分比
  double _getSignalPercent(int rssi) {
    // RSSI范围在-100到-30之间，转换为0-100%
    return ((rssi + 100) / 70 * 100).clamp(0.0, 100.0);
  }

  // 获取信号强度颜色
  Color _getSignalColor(double percent) {
    if (percent > 70) return Colors.green;
    if (percent > 40) return Colors.orange;
    return Colors.red;
  }

  // 开始持续扫描
  void _startScan() async {
    await _requestPermissions();

    setState(() {
      _isScanning = true;
    });

    // 清理之前的扫描和定时器
    FlutterBluePlus.stopScan();
    _debounceTimer?.cancel();

    // 创建制造商数据过滤器
    final manufacturerId = 0x4C;
    final data = [0x12, 0x19, 0x10];
    final mask = [0xFF, 0x00, 0x18];

    final msdFilter = MsdFilter(manufacturerId, data: data, mask: mask);

    // 开始一次持续扫描（不设置timeout）
    FlutterBluePlus.startScan(
        withRemoteIds: widget.macs,
        withMsd: [msdFilter],
        androidScanMode: AndroidScanMode.lowLatency, // 低延迟模式
        continuousUpdates: true);

    // 监听持续扫描结果
    FlutterBluePlus.scanResults.listen((results) {
      for (var r in results) {
        String mac = r.device.remoteId.toString();
        // 过滤出在macs列表中的设备
        if (widget.macs.contains(mac.toUpperCase())) {
          AccessoryBatteryStatus? batteryStatus;
          var md = r.advertisementData.manufacturerData[manufacturerId];
          if (md != null) {
            int status = md[2];
            switch ((status >> 6) & 0x3) {
              // get highest 2 bits
              case 0:
                batteryStatus = AccessoryBatteryStatus.ok;
                break;
              case 1:
                batteryStatus = AccessoryBatteryStatus.medium;
                break;
              case 2:
                batteryStatus = AccessoryBatteryStatus.low;
                break;
              case 3:
                batteryStatus = AccessoryBatteryStatus.criticalLow;
                break;
              default:
                batteryStatus = AccessoryBatteryStatus.ok;
            }
          }
          // 使用防抖定时器避免频繁更新
          _debounceTimer?.cancel();
          _debounceTimer = Timer(_debounceDuration, () {
            if (!_isScanning || !mounted || !context.mounted) return;
            setState(() {
              if (!mounted) return;
              _deviceSignalMap[mac] = r.rssi;
              _lastUpdateTimes[mac] = DateTime.now();
              _deviceBatteryMap[mac] = batteryStatus;
            });
          });
        }
      }
    });
  }

  // 停止扫描
  void _stopScan() {
    if (_isScanning) {
      FlutterBluePlus.stopScan();
      _debounceTimer?.cancel();
      if (!mounted || !context.mounted) return;
      setState(() {
        _isScanning = false;
      });
    }
  }

  // 请求权限
  Future<void> _requestPermissions() async {
    await Permission.bluetoothScan.request();
    await Permission.bluetoothConnect.request();
    await Permission.location.request();
    await Permission.locationAlways.request();
  }

  // 显示错误对话框
  void _showErrorDialog(String message) {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: Text('错误'),
        content: Text(message),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('确定'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('定位标签蓝牙信号扫描'), centerTitle: true),
      body: Column(
        children: [
          // 扫描控制区域
          Padding(
            padding: EdgeInsets.all(16),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton(
                  onPressed: _isScanning ? _stopScan : _startScan,
                  child: Text(_isScanning ? '停止扫描' : '开始扫描'),
                  style: ElevatedButton.styleFrom(
                    minimumSize: Size(150, 50),
                  ),
                ),
              ],
            ),
          ),

          // 扫描状态指示器
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _isScanning
                    ? Row(
                        children: [
                          Icon(
                            Icons.bluetooth_searching,
                            color: Colors.blue,
                          ),
                          SizedBox(width: 10),
                          Text('持续扫描中...'),
                          SizedBox(width: 10),
                          _buildConnectionIndicator(),
                        ],
                      )
                    : Text(
                        '准备扫描',
                        style: TextStyle(color: Colors.grey),
                      ),
              ],
            ),
          ),

          // 设备列表
          Expanded(
            child: _deviceSignalMap.isEmpty
                ? Center(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Icon(
                          Icons.bluetooth_disabled,
                          size: 80,
                          color: Colors.grey,
                        ),
                        SizedBox(height: 20),
                        Text(
                          '未检测到设备',
                          style: TextStyle(
                            color: Colors.grey,
                            fontSize: 18,
                          ),
                        ),
                      ],
                    ),
                  )
                : ListView.builder(
                    itemCount: _deviceSignalMap.length,
                    itemBuilder: (context, index) {
                      final deviceId = _deviceSignalMap.keys.toList()[index];
                      final rssi = _deviceSignalMap[deviceId]!;
                      final signalPercent = _getSignalPercent(rssi);
                      final signalColor = _getSignalColor(signalPercent);
                      final lastUpdate = _lastUpdateTimes[deviceId];
                      final formattedTime =
                          _formatTimeAgo(lastUpdate!); // 使用格式化后的时间
                      final batteryStatus = _deviceBatteryMap[deviceId];

                      return Card(
                        margin:
                            EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                        child: ListTile(
                          leading: Container(
                            width: 60,
                            height: 60,
                            child: Stack(
                              alignment: Alignment.center,
                              children: [
                                CircularProgressIndicator(
                                  value: signalPercent / 100,
                                  backgroundColor: Colors.grey[300],
                                  color: signalColor,
                                  strokeWidth: 4,
                                ),
                                Text(
                                  '${signalPercent.toStringAsFixed(0)}%',
                                  style: TextStyle(
                                    fontSize: 12,
                                    fontWeight: FontWeight.bold,
                                    color: signalColor,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          title: Text(
                            'MAC: $deviceId',
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                          subtitle: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                children: [
                                  Text(
                                    '电量: ',
                                    style: TextStyle(
                                      fontSize: 16,
                                      fontWeight: FontWeight.w600,
                                      color: Colors.black87,
                                    ),
                                  ),
                                  _buildBatteryIcon(batteryStatus)
                                ],
                              ),
                              SizedBox(height: 5),
                              Text(
                                '信号强度: ${rssi} dBm',
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: FontWeight.w600,
                                  color: Colors.black87,
                                ),
                              ),
                              SizedBox(height: 5),
                              Row(
                                children: [
                                  Expanded(
                                    child: Text(
                                      '信号质量: ${signalPercent.toStringAsFixed(1)}%',
                                      style: TextStyle(
                                        color: signalColor,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ),
                                  Container(
                                    padding: EdgeInsets.symmetric(
                                        horizontal: 8, vertical: 4),
                                    decoration: BoxDecoration(
                                      color: signalColor.withOpacity(0.1),
                                      borderRadius: BorderRadius.circular(12),
                                    ),
                                    child: Text(
                                      '实时',
                                      style: TextStyle(
                                        color: signalColor,
                                        fontSize: 12,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                              SizedBox(height: 5),
                              Row(
                                children: [
                                  Icon(
                                    Icons.timer,
                                    size: 16,
                                    color: Colors.grey,
                                  ),
                                  SizedBox(width: 4),
                                  Text(
                                    '检测于 $formattedTime',
                                    style: TextStyle(
                                      fontSize: 12,
                                      color: Colors.grey,
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                      );
                    },
                  ),
          ),
        ],
      ),
    );
  }

  Widget _buildBatteryIcon(AccessoryBatteryStatus? batteryStatus) {
    switch (batteryStatus) {
      case AccessoryBatteryStatus.ok:
        return const Icon(Icons.battery_full, color: Colors.green, size: 15);
      case AccessoryBatteryStatus.medium:
        return const Icon(Icons.battery_4_bar, color: Colors.orange, size: 15);
      case AccessoryBatteryStatus.low:
        return const Icon(Icons.battery_2_bar, color: Colors.red, size: 15);
      case AccessoryBatteryStatus.criticalLow:
        return const Icon(Icons.battery_alert, color: Colors.red, size: 15);
      default:
        return const SizedBox(width: 0);
    }
  }

  Widget _buildInfoCard(String title, String value, IconData icon) {
    return Column(
      children: [
        Icon(
          icon,
          size: 24,
          color: Colors.blue,
        ),
        SizedBox(height: 4),
        Text(
          title,
          style: TextStyle(
            fontSize: 12,
            color: Colors.grey[600],
          ),
        ),
        Text(
          value,
          style: TextStyle(
            fontSize: 16,
            fontWeight: FontWeight.bold,
            color: Colors.black87,
          ),
        ),
      ],
    );
  }

  Widget _buildConnectionIndicator() {
    return AnimatedContainer(
      duration: Duration(milliseconds: 500),
      height: 8,
      width: 8,
      decoration: BoxDecoration(
        shape: BoxShape.circle,
        color: _isScanning ? Colors.green : Colors.grey,
      ),
    );
  }
}
